
<template>
    <el-tabs v-model="editableTabsValue" type="card" closable @tab-remove="removeTab" @tab-click="clickTab" >
      <el-tab-pane
        v-for="(item, index) in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
      >
      </el-tab-pane>
    </el-tabs>
</template>

<script>
  export default {
    name: "Tabs",
    data() {
      return {
      }
    },
    //  computed 是基于它的依赖缓存，只有相关依赖发生改变时才会重新取值
    computed: {
        editableTabsValue: {
            get(){
                return this.$store.state.menus.editableTabsValue
            },
            set(val){
                this.$store.state.menus.editableTabsValue = val
            }
        },
        editableTabs: {
            get(){
                return this.$store.state.menus.editableTabs
            },
            set(val){
                this.$store.state.menus.editableTabs = val
            }
        }

    },
    methods: {
        //点击由路由去跳转到对应的路由对象名称，选中的事件交由App.vue里的watch去监听路由对象改变去添加到标签栏和选中
      clickTab(target){
        this.$router.push({name: target.props.name})
      },
      removeTab(targetName) {
          let tabs = this.editableTabs;
          let activeName = this.editableTabsValue;
          // 首页不能删除
          if (targetName === "Home") {
              return
          }
          // 如果删除到了当前标签选中项，则需重新寻找最近的右边有没有，没有则选中左边
          if (activeName === targetName) {
              tabs.forEach((tab, index) => {
                  if (tab.name === targetName) {
                      let nextTab = tabs[index + 1] || tabs[index - 1];
                      if (nextTab) {
                          activeName = nextTab.name;
                      }
                  }
              });
          }
          this.editableTabsValue = activeName;
          //删除存在标签里面对应的标签项
          this.editableTabs = tabs.filter(tab => tab.name !== targetName);
          this.$router.push({name: activeName})
      },
    },
  }
</script>

<style>

</style>
